package com.ruoyi.ring.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.ring.domain.RingHeartRateInfo;
import com.ruoyi.ring.domain.RingSleepDetail;
import com.ruoyi.ring.domain.RingSportDetail;
import com.ruoyi.ring.domain.dto.RingHrvInfoDTO;
import com.ruoyi.ring.domain.vo.RingHeartRateInfoVO;
import com.ruoyi.ring.domain.vo.RingHrvInfoVO;
import com.ruoyi.ring.mapper.RingSleepDetailMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ring.mapper.RingHrvInfoMapper;
import com.ruoyi.ring.domain.RingHrvInfo;
import com.ruoyi.ring.service.IRingHrvInfoService;

import javax.annotation.Resource;

/**
 * 心率变异性历史心率Service业务层处理
 * 
 * @author liuwp
 * @date 2025-08-22
 */
@Service
public class RingHrvInfoServiceImpl implements IRingHrvInfoService 
{
    @Resource
    private RingHrvInfoMapper ringHrvInfoMapper;

    /**
     * 查询心率变异性历史心率
     * 
     * @param id 心率变异性历史心率主键
     * @return 心率变异性历史心率
     */
    @Override
    public RingHrvInfo selectRingHrvInfoById(Long id)
    {
        return ringHrvInfoMapper.selectRingHrvInfoById(id);
    }

    /**
     * 查询心率变异性历史心率列表
     * 
     * @param ringHrvInfo 心率变异性历史心率
     * @return 心率变异性历史心率
     */
    @Override
    public List<RingHrvInfo> selectRingHrvInfoList(RingHrvInfo ringHrvInfo)
    {
        return ringHrvInfoMapper.selectRingHrvInfoList(ringHrvInfo);
    }

    /**
     * 根据业务主键查询一条记录：心率变异性历史心率
     *
     * @param ringHrvInfo 心率变异性历史心率
     * @return 心率变异性历史心率
     */
    @Override
    public RingHrvInfo selectOneRingHrvInfo(RingHrvInfo ringHrvInfo)
    {
        return ringHrvInfoMapper.selectOneRingHrvInfo(ringHrvInfo);
    }

    /**
     * 新增心率变异性历史心率
     * 
     * @param ringHrvInfo 心率变异性历史心率
     * @return 结果
     */
    @Override
    public int insertRingHrvInfo(RingHrvInfo ringHrvInfo)
    {
        ringHrvInfo.setCreateTime(DateUtils.getNowDate());
        return ringHrvInfoMapper.insertRingHrvInfo(ringHrvInfo);
    }

    /**
     * 修改心率变异性历史心率
     * 
     * @param ringHrvInfo 心率变异性历史心率
     * @return 结果
     */
    @Override
    public int updateRingHrvInfo(RingHrvInfo ringHrvInfo)
    {
        ringHrvInfo.setUpdateTime(DateUtils.getNowDate());
        return ringHrvInfoMapper.updateRingHrvInfo(ringHrvInfo);
    }

    @Override
    public int updateRingHrvInfoCondition(RingHrvInfo ringHrvInfo, RingHrvInfo ringHrvInfoCondition)
    {
                ringHrvInfo.setUpdateTime(DateUtils.getNowDate());
        return ringHrvInfoMapper.updateRingHrvInfoCondition(ringHrvInfo, ringHrvInfoCondition);
    }

    /**
     * 批量删除心率变异性历史心率
     * 
     * @param ids 需要删除的心率变异性历史心率主键
     * @return 结果
     */
    @Override
    public int deleteRingHrvInfoByIds(Long[] ids)
    {
        return ringHrvInfoMapper.deleteRingHrvInfoByIds(ids);
    }

    /**
     * 删除心率变异性历史心率信息
     * 
     * @param id 心率变异性历史心率主键
     * @return 结果
     */
    @Override
    public int deleteRingHrvInfoById(Long id)
    {
        return ringHrvInfoMapper.deleteRingHrvInfoById(id);
    }

    /**
     * 条件删除心率变异性历史心率
     *
     * @param ringHrvInfo 心率变异性历史心率
     * @return 结果
     */
    @Override
    public int deleteRingHrvInfoByCondition(RingHrvInfo ringHrvInfo)
    {
        return ringHrvInfoMapper.deleteRingHrvInfoByCondition(ringHrvInfo);
    }

    @Override
    public RingHrvInfoVO queryRingHrvInfo(RingHrvInfoDTO ringHrvInfoDTO) {
        String type = ringHrvInfoDTO.getType();
        List<RingHrvInfo> list = ringHrvInfoMapper.queryRingHrvInfoList(ringHrvInfoDTO);
        RingHrvInfoVO ringHrvInfoVO = new RingHrvInfoVO();
        long count = 0;//周和月 一共有多少个测量节点   后续看情况是否是全部节点
        long sum = 0;//计算所有总数
        if("1".equals(type) && list.size() > 0){
            RingHrvInfo hrvInfo = list.get(0);
            String[] hrvInfos = Arrays.stream(hrvInfo.getHrvList().split(","))
                    .filter(s -> s != null && !s.equalsIgnoreCase("null") && !s.isEmpty())
                    .toArray(String[]::new);
//            // 分割字符串，将"null"替换为0，然后转换为int数组
//            int[] hrvInfos1 = Arrays.stream(hrvInfo.getHrvList().split(","))
//                    .map(s -> "null".equalsIgnoreCase(s) ? "0" : s)  // 将null字符串替换为"0"
//                    .mapToInt(Integer::parseInt)  // 转换为int
//                    .toArray();
            int[] hrvs = Stream.of(hrvInfos).mapToInt(Integer::parseInt).toArray();//转成int数组
            ringHrvInfoVO.setAverageValue((int) Arrays.stream(hrvs).filter(num -> num != 0).average().orElse(0));
            List<RingHrvInfoVO.RingHrv> ringHrvList = new ArrayList<>();
            int timeInterval = 24*60/hrvs.length;
            for(int i = 0; i< hrvs.length; i++){
                int rate = hrvs[i];
                RingHrvInfoVO.RingHrv ringHrv = new RingHrvInfoVO.RingHrv();
                // 计算当前时间（分钟）：初始0分钟，每次增加5分钟
                int minutes = i * timeInterval;
                ringHrv.setTimeLabel(DateUtils.convertMinutesToHHMM(minutes));
                ringHrv.setValue(String.valueOf(rate));
                ringHrvList.add(ringHrv);
            }
            ringHrvInfoVO.setHrvList(ringHrvList);
        }
        if(("2".equals(type) || "3".equals(type)) && list.size() > 0){
            List<RingHrvInfoVO.RingHrv> ringHrvList = new ArrayList<>();
            for (RingHrvInfo hrvInfo : list){
                String[] hrvInfos = Arrays.stream(hrvInfo.getHrvList().split(","))
                        .filter(s -> s != null && !s.equalsIgnoreCase("null") && !s.isEmpty())
                        .toArray(String[]::new);
                long everyDaySum = Stream.of(hrvInfos).mapToInt(Integer::parseInt).sum();//计算一天总数
                sum += everyDaySum;//计算所有已测节点心率总数
                long num = Stream.of(hrvInfos).map(Integer::parseInt).filter(r -> r != 0 && r != 255).count();  // .collect(Collectors.toList());   一天多少测量节点
                count += num;//计算所有已测节点总数
                String result = Stream.of(hrvInfos)
                        .map(Integer::parseInt)                // 转换为整数
                        .filter(r -> r != 0 && r != 255)        // 过滤掉0和255
                        .sorted()                               // 从小到大排序
                        .map(String::valueOf)                   // 转换回字符串
                        .collect(Collectors.joining(","));
                RingHrvInfoVO.RingHrv ringHrv = new RingHrvInfoVO.RingHrv();
                ringHrv.setTimeLabel(queryWeekday(hrvInfo.getHistoryDay(),type));
                ringHrv.setValue(result);
                ringHrvList.add(ringHrv);
            }
            long value = sum/count;
            ringHrvInfoVO.setAverageValue((int)value);
            ringHrvInfoVO.setHrvList(ringHrvList);
        }
        return ringHrvInfoVO;
    }

    @Override
    public String queryPlanHrvInfo() {
        String averageHrv = "暂未形成基线";
        // 获取当前日期
        Date currentDate = new Date();
        LocalDate currentLocalDate = currentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate lastMonthLocalDate = currentLocalDate.minusMonths(1);
        Date lastMonthDate = Date.from(lastMonthLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        List<RingHrvInfo> ringHrvInfos = ringHrvInfoMapper.queryPlanHrvInfo(lastMonthDate);
        if(ringHrvInfos.size() > 0){
            LocalDate localDate = lastMonthDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            // 获取当月的天数
            int daysInMonth = localDate.lengthOfMonth();
            if(daysInMonth == ringHrvInfos.size()){
                int totalCount = 0;
                int totalSum = 0;
                for(RingHrvInfo ringHrvInfo : ringHrvInfos){
                    String[] hrvInfos = Arrays.stream(ringHrvInfo.getHrvList().split(","))
                            .filter(s -> s != null && !s.equalsIgnoreCase("null") && !s.isEmpty())
                            .toArray(String[]::new);
                    totalCount += (int)Stream.of(hrvInfos).mapToInt(Integer::parseInt).filter(r -> r != 0 && r != 255).count();
                    totalSum += Stream.of(hrvInfos).mapToInt(Integer::parseInt).filter(r -> r != 0 && r != 255).sum();//计算一天总数
                }
                averageHrv = String.valueOf(totalSum/totalCount);
            }
        }
        return averageHrv;
    }

    public String queryWeekday(Date historyDay, String type) {
        String chineseDay = "";
        // 创建Calendar实例并设置时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(historyDay);
        if("2".equals(type)){
            // 获取星期几（1=周日，2=周一，...，7=周六）
            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
            // 中文星期数组（索引0对应周日，1对应周一...6对应周六）
            String[] chineseWeekdays = {"日", "一", "二", "三", "四", "五", "六"};
            // 根据星期数值获取对应的中文名称
            chineseDay = chineseWeekdays[dayOfWeek - 1];
        }
        if("3".equals(type)){
            // 获取当月的第几天（1-31）
            chineseDay = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
        }
        return chineseDay;
    }
}
